<template>
  <div class="supplier-management">
    <div class="page-title">供应商管理</div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="供应商编码">
          <el-input v-model="searchForm.suCode" placeholder="请输入供应商编码" clearable />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input v-model="searchForm.suName" placeholder="请输入供应商名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增供应商
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table :data="supplierList" stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" v-if="false"/>
        <el-table-column prop="suCode" label="供应商编码" />
        <el-table-column prop="suName" label="供应商名称" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="createBy" label="创建人" />
        <el-table-column prop="updateTime" label="修改时间" width="180" />
        <el-table-column prop="updateBy" label="修改人" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope" >
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 供应商表单弹窗 -->
    <SupplierForm
      :visible="formVisible"
      @update:visible="formVisible = $event"
      :form-data="formData"
      @submit="handleFormSubmit"
      @close="handleFormClose" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { request } from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 导入组件
import SupplierForm from './SupplierForm.vue'

// 响应式数据
const loading = ref(false)
const supplierList = ref([])
const formVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  suCode: '',
  suName: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  id: '',
  suCode: '',
  suName: '',
  remaker: ''
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      filter: {
        pageIndex: pagination.current,
        pageSize: pagination.size,
        orderBy: "createTime",
        isAscending: true
      },
      supplier: {
        ...searchForm
      }
    }
    
    // 调用后端API
    const response = await request.post('/Supplier/Supplier_Page', params)
    supplierList.value = response.data
    pagination.total = response.totalCount
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  loadData()
}

// 新增
const handleAdd = () => {
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
  formVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  // 填充表单数据
  Object.keys(formData).forEach(key => {
    if (row[key] !== undefined && row[key] !== null) {
      formData[key] = row[key]
    }
  })
  formVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除供应商 "${row.suName}" 吗？`, '提示', {
      type: 'warning'
    })
    
    // 调用删除API
    await request.delete(`/Supplier/${row.id}`)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    console.log('删除取消或失败')
  }
}

// 表单提交处理
const handleFormSubmit = async (formData) => {
  try {
    if (formData.id) {
      // 编辑
      await request.post('/Supplier/SupplierSave', formData)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await request.post('/Supplier/SupplierSave', formData)
      ElMessage.success('创建成功')
    }
    
    formVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 表单关闭处理
const handleFormClose = () => {
  // 可以在这里添加关闭后的清理逻辑
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = page
  loadData()
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.supplier-management {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style>